//
//  HNSH_ChatFriendViewController.m
//  HNSH_SingleProject
//
//  Created by 李宇廷 on 2023/2/16.
//

#import "HNSH_ChatFriendViewController.h"
#import "HNSH_ChatFriendCell.h"
#import "HNSH_ChatFriendHeader.h"

//vc
#import "HNSH_ChatFriendDetailViewController.h"
#import "HNSH_NewFriendViewController.h"
#import "HNSH_GroupListViewController.h"

@interface HNSH_ChatFriendViewController ()

/* listAry */
@property (nonatomic, strong) NSMutableArray *listAry;
/** */
@property (nonatomic, copy)NSArray * titlesArray;
/** */
@property (nonatomic, strong)NSMutableDictionary * mDic;

/* topView */
@property (nonatomic, strong) HNSH_ChatFriendHeader *topView;

@end

static NSString *HNSH_ChatFriendCellID = @"HNSH_ChatFriendCellID";

@implementation HNSH_ChatFriendViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self loadRongCloudFriendshipList];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self configTableView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(txlUnreadCountNiti:) name:@"KTXLUnreadCountNiti" object:nil];
}

- (void)txlUnreadCountNiti:(NSNotification *)sender {
    NSDictionary *dic = sender.userInfo;
    NSInteger count = [dic[@"count"] integerValue];
    self.topView.unreadCount = count;
}

- (void)configTableView {
    [self.tableView registerClass:[HNSH_ChatFriendCell class] forCellReuseIdentifier:HNSH_ChatFriendCellID];
    self.tableView.rowHeight = 52;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    HNSH_ChatFriendHeader *headerView = [[HNSH_ChatFriendHeader alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 100)];
    self.topView = headerView;
    WeakSelf(weakSelf);
    headerView.indexBlock = ^(NSInteger index) {
        if (index == 0) {//新的朋友
            weakSelf.topView.unreadCount = 0;
            HNSH_NewFriendViewController *vc = [[HNSH_NewFriendViewController alloc]init];
            [weakSelf.navigationController pushViewController:vc animated:YES];
        } else if (index == 1) {//我的群聊
            HNSH_GroupListViewController *vc = [[HNSH_GroupListViewController alloc]init];
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }
    };
    self.tableView.tableHeaderView = headerView;
}

#pragma mark Networking
//获取好友列表
- (void)loadRongCloudFriendshipList {
    [HNSH_ChatNetServer requestRongCloudFriendshipListSuccess:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            self.listAry = [NSMutableArray arrayWithArray:[NSArray yy_modelArrayWithClass:[HNSH_ChatFriendModel class] json:responseObject.resultset]];
            [self setDefaultData];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

//MARK: 数据源排序
- (void)setDefaultData{
    self.mDic = [NSMutableDictionary new];
    NSArray * oriArray = self.listAry;
    for (HNSH_ChatFriendModel * model in oriArray) {
        NSString * name = model.user.display_name.length ? model.user.display_name : model.user.name;
        if (name && name.length) {
            NSString * cityMutableString = [NSMutableString stringWithString:name];
            CFStringTransform((__bridge CFMutableStringRef)cityMutableString, NULL, kCFStringTransformMandarinLatin, NO);
            CFStringTransform((__bridge CFMutableStringRef)cityMutableString, NULL, kCFStringTransformStripCombiningMarks, NO);
            NSString * firstLetter = [[cityMutableString uppercaseString] substringToIndex:1];
            if (![NSString judgeString:firstLetter]) {
                firstLetter = @"#";
            }
            if ([self.mDic objectForKey:firstLetter]) {
                NSMutableArray * mCityArray = self.mDic[firstLetter];
                if (mCityArray) {
                    [mCityArray addObject:model];
                    self.mDic[firstLetter] = mCityArray;
                } else {
                    self.mDic[firstLetter] = [NSMutableArray arrayWithArray:@[model]];
                }
            } else {
                [self.mDic setObject:[NSMutableArray arrayWithArray:@[model]] forKey:firstLetter];
            }
        }
    }
    self.titlesArray = [self reqDiction:self.mDic];
    [self.tableView reloadData];
}
- (NSArray *)reqDiction:(NSDictionary *)dict{
    NSArray * allKeyArray = [dict allKeys];
    NSArray * afterSortKeyArray = [allKeyArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        NSComparisonResult resuest = [obj1 compare:obj2];
        return resuest;
    }];
    //通过排列的key值获取value
    NSMutableArray * valueArray = [NSMutableArray array];
    for (NSString * sortsing in afterSortKeyArray) {
        NSString * valueString = [dict objectForKey:sortsing];
        [valueArray addObject:valueString];
    }
    return afterSortKeyArray;
}

#pragma mark - delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.titlesArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSString * key = self.titlesArray[section];
    NSArray * arr = self.mDic[key];
    return arr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 44.0f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01f;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 44)];
    view.backgroundColor = [UIColor appWhiteLabelColor];
    UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(16, 0, view.width - 40, view.height)];
    label.textColor = [UIColor appGray666LabelColor];
    label.font = [UIFont boldSystemFontOfSize:14];
    NSString * key = self.titlesArray[section];
    label.text = key;
    [view addSubview:label];
    return view;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HNSH_ChatFriendCell *cell = [tableView dequeueReusableCellWithIdentifier:HNSH_ChatFriendCellID];
    NSString * key = self.titlesArray[indexPath.section];
    NSArray * arr = self.mDic[key];
    cell.model = arr[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString * key = self.titlesArray[indexPath.section];
    NSArray * arr = self.mDic[key];
    HNSH_ChatFriendModel * model = arr[indexPath.row];
    HNSH_ChatFriendDetailViewController * vc = [HNSH_ChatFriendDetailViewController new];
    vc.rcUserId = model.user.uid;
    [self.navigationController pushViewController:vc animated:YES];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    return self.titlesArray[section];
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    return self.titlesArray;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{
    [self.view makeToast:title];
    return index;
}

#pragma mark lazy
- (NSMutableArray *)listAry {
    if (!_listAry) {
        _listAry = [NSMutableArray arrayWithCapacity:0];
    }
    return _listAry;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
